//
//  SRArchiveObject.m
//  ExpressionTest
//
//  Created by Charles on 16/9/18.
//  Copyright © 2016年 Charles. All rights reserved.
//

#import "SRArchiveObject.h"
#import <objc/runtime.h>

@implementation SRArchiveObject

-(id)initWithCoder:(NSCoder *)decode{
    if (self = [super init]) {
        
//        _roomId = [decode decodeObjectForKey:@"roomId"];
        
        Class cls = self.class;
        NSArray * propertyNames = [self propertyNames];
        for (int i = 0; i<propertyNames.count; i++) {
            NSString * strName = propertyNames[i];
            const char * name = [strName cStringUsingEncoding:NSUTF8StringEncoding];
            Ivar p_name = class_getInstanceVariable(cls, name);
            object_setIvar(self, p_name, [decode decodeObjectForKey:strName]);
        }
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder{
//    [encoder encodeObject:_roomId forKey:@"roomId"];

    Class cls = self.class;
    NSArray * propertyNames = [self propertyNames];
    for (int i = 0; i<propertyNames.count; i++) {
        NSString * strName = propertyNames[i];
        const char * name = [strName cStringUsingEncoding:NSUTF8StringEncoding];
        Ivar p_name = class_getInstanceVariable(cls, name);
        [encoder encodeObject:(__bridge id)(p_name) forKey:strName];
    }
}


- (NSArray *)propertyNames{
    Class cls = self.class;
    unsigned int count;// 记录属性个数
    objc_property_t *properties = class_copyPropertyList(cls, &count);
    // 遍历
    NSMutableArray *mArray = [NSMutableArray array];
    for (int i = 0; i < count; i++) {
        // objc_property_t 属性类型
        objc_property_t property = properties[i];
        // 获取属性的名称 C语言字符串
        const char *propertyName = property_getName(property);
        // 转换为Objective C 字符串
        NSString *name = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding];
        [mArray addObject:name];
    }
    return mArray.copy;
}

@end
